package com.rongzhe.house.common.interceptor;

import com.rongzhe.house.common.cache.WebCacheUtil;
import com.rongzhe.house.common.constants.Constants;
import com.rongzhe.house.common.utils.Base64Util;
import com.rongzhe.house.login.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局拦截器
 */
public class GlobalInterceptor implements HandlerInterceptor {

    @Autowired
    private WebCacheUtil webCacheUtil;

    //在请求处理之前进行调用（Controller方法调用之前
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        User user=(User)httpServletRequest.getSession().getAttribute(Constants.USER_LOGIN_KEY);
        String cookieValue="";
        if(null==user) {
            cookieValue = webCacheUtil.init(httpServletRequest, httpServletResponse).getCookieValue(Constants.USER_LOGIN_KEY);
            if (null != cookieValue && cookieValue != "") {
                cookieValue = new String(Base64Util.decode(cookieValue), "UTF-8");
                String[] data = cookieValue.split(",");
                User u = new User();
                u.setId(Integer.valueOf(data[0]));
                u.setNickName(data[1]);
                user = u;
            }
        }
        if(null!=user){
            httpServletRequest.getSession().setAttribute(Constants.USER_LOGIN_KEY, user);
        }
        return true;    //如果false，停止流程，api被拦截
    }

    //请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    //在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}